package com.example.damaizuul.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/6/26
 * Email haijunzhou@hnit.edu.cn
 */
@Component
public class AccessTokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // /showCar
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        if (request.getServletPath().equals("/showCar")) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        if (request.getParameter("accessToken")==null) {
            currentContext.getResponse().setHeader("AAAAAA","AAAAA");

            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            Map<String,Object> result = new HashMap<>();
            result.put("code",0);
            result.put("msg","请先登录系统");
            result.put("data",null);
            ObjectMapper mapper = new ObjectMapper();
            try {
                String json = mapper.writeValueAsString(result);
                currentContext.setResponseBody(json);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
